package com.cross.sql;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;

import com.cross.core.AbstractWriter;
import com.cross.core.Column;
import com.cross.core.Header;
import com.cross.core.Item;

public class SimpleSQLWriter extends AbstractWriter {

	private String table = "table";
	private Writer writer;

	public SimpleSQLWriter(Header header, File file, String table) throws IOException {
		this.table = table;
		super.setHeader(header);
		writer = new FileWriter(file);
	}

	@Override
	public boolean available() {
		return true;
	}

	@Override
	public void close() {
		try {
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void writeRow() {
		StringBuffer sql = new StringBuffer();
		List<Item> items = currentRow.getItems();
		Item item = null;
		sql.append("insert into ");
		sql.append(table);
		sql.append(" (");
		for (Column column : header.getColumns()) {
			sql.append(column.getTitle());
			sql.append(",");
		}
		int last = sql.lastIndexOf(",");
		if (-1 == last) {
			return;
		}
		sql.deleteCharAt(sql.lastIndexOf(","));
		sql.append(") values ('");
		for (Column column : header.getColumns()) {
			item = currentRow.getItem(column.getNumber());
			sql.append(item.getString());
			sql.append("','");
		}
		last = sql.lastIndexOf("','");
		if (-1 == last) {
			return;
		}
		sql.delete(last+1, sql.length());
		sql.append(");\r\n");
		try {
			writer.write(sql.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
